<template>
    <div class="bg">
        <div class="header">
            <router-link class="header-btnLeft" to="./"><img src="../assets/tabBar-home.png"></router-link>
            <h1 class="header-title">登录</h1>
            <div class="header-btnRight"></div>
        </div>
        <div class="h120"></div>
        <div v-if="!isWechat">
            <div class="login">
                <form>
                    <div class="login-item">
                        <TelCode :phoneCode="phoneCode" v-on:phoneCodeFn="phoneCodeFn" ></TelCode>
                        <input type="text" name="username" v-model="username" placeholder="请输入手机号码"/>
                    </div>
                    <div class="login-item">
                        <input type="password" name="password" v-model="password" placeholder="请输入动态密码" autocomplete=''/>
                        <div :class="getCodeState ? 'login-disabled' :'login-code'" @click="getRegCode">{{regCode}}</div>
                    </div>
                </form>
            </div>
            <div class="login-btn">
                <button  class="login-btn-login" @click="login">登录</button>
            </div>

            <!-- <div class="login">
                 <form>
                     <div class="login-item">
                         <TelCode :phoneCode="phoneCode" v-on:phoneCodeFn="phoneCodeFn" ></TelCode>
                         <input type="text" name="username" v-model="username" placeholder="请输入手机号码/邮箱"/>
                     </div>
                     <div class="login-item"><input type="password" name="password" v-model="password" placeholder="请输入密码" autocomplete=''/></div>
                 </form>
             </div>

             <div class="login-btn">
                 <button  class="login-btn-login" @click="login">登录</button>
                 <button class="login-btn-reg" @click="regPhone">手机号注册</button>
                 <div class="login-other">
                     <router-link to="./my-reg-email">邮箱注册</router-link>
                     <router-link to="./my-get-password">忘记密码</router-link>
                 </div>
             </div> -->
        </div>

        <div v-else class="login-weChat">
            <img class="login-weChat-logo" src="../assets/weChat.png">
            <router-link class="login-weChat-name" to="">微信登录</router-link>
        </div>

    </div>
</template>

<script>
    import { Toast } from 'mint-ui';
    import store from "../store/store"
    import serve from "../store/serve"
    import storage from "../store/localstorage"
    import * as types from '../store/types'
    import TelCode from '../components/TelCode';
    import crypto from 'crypto'
    import judgeURL from '../store/judgeURL'

    export default {
        name: "My-login",
        components:{
            TelCode
        },
        data(){
            return{
                clientId: null,
                loginKey: null,
                fTryAutoLogin: false,
                fullUsername: null,
                phoneCode:'+86',
                username:'',
                password:'',
                redirect:'',
                regCode:'获取动态密码',
                getCodeState:false,
            }
        },
        methods:{
            getRegCode(){
                if(!this.username && this.username.length<2){
                    Toast({
                        message: '请输入手机号',
                        duration: 1000
                    });
                    return false
                }
                if(this.getCodeState){
                    return;
                }
                var params={
                    telphone:this.username,
                    country_code:this.phoneCode
                }
                this.getCodeState = true;
                this.axios.postAll('api/member/GetTelCode', params).then((res)=>{
                    if(res.data.code == 0){//验证码发送成功
                        // Toast({message: '验证码：'+res.data.data.code,duration: 1500});
                        Toast({message: res.data.msg,duration: 1500});
                        let codeCount = 60;//验证码倒计时
                        this.regCode = codeCount + 's后重新获取'
                        let timer = setInterval(()=>{
                            codeCount -= 1;
                            this.regCode = codeCount + 's后重新获取'
                            if(codeCount <= 0){
                                this.regCode = '获取动态密码'
                                this.getCodeState = false;
                                clearInterval(timer);
                            }
                        },1000)
                    }else{
                        this.getCodeState = false;
                        Toast({message:res.data.msg,duration: 1000});
                    }

                }).catch(err => console.log(err));

            },
            phoneCodeFn(val){
                this.phoneCode=val;
            },
            login(){
                if(!this.username && this.username.length<2){
                    Toast({
                        message: '请输入手机号或邮箱',
                        duration: 1000
                    });
                    return false
                }
                // if(!this.password && this.password.length<6){
                //     Toast({
                //         message: '请输入密码',
                //         duration: 1000
                //     });
                //     return false
                // }
                if(!this.password && this.password.length<4){
                    Toast({
                        message: '请输入验证码',
                        duration: 1000
                    });
                    return false
                }
                if (!this.phoneCode || this.phoneCode == '电话区号') {
                    Toast({message: '请选择正确的国家（地区）代码',duration: 1000});
                    return false;
                }

                // var params={
                //     country_code:this.phoneCode,
                //     username:this.username,
                //     password:this.password
                // }
                // this.axios.post('api/member/login', params)
                //     .then(res => {
                //         Toast({message: '恭喜您，登录成功！',duration: 1000});
                //         storage.set('userinfo',res.data)
                //         store.commit(types.LOGIN, res.data.token)

                //         res.data.Integral.forEach((item)=>{
                //             if (item.types==1){
                //                 storage.set('product_integra',item)
                //             } else if (item.types == 2){
                //                 storage.set('comment_integra', item)
                //             }
                //         })

                //         setTimeout(()=>{
                //             this.$router.push({path:'/my'})
                //         },1000)
                //     })
                //     .catch(err => console.log(err));

                // 验证码登录
                let _params={
                    country_code:this.phoneCode,
                    telphone:this.username,
                    username:this.username,
                    order_id:window.localStorage.share_order_id || '',
                    // thumb: false,
                    // qita: false,
                    code:this.password,
                    //
                    partner_id:storage.get('partner_id') ||'',
                }
                this.axios.post('api/member/checkTelCode', _params)
                    .then(res => {
                        Toast({message: '恭喜您，登录成功！',duration: 1000});
                        storage.set('userinfo',res.data)
                        store.commit(types.LOGIN, res.data.token)
                        storage.set('partner_id',res.data.partner_id)
//                        window.localStorage.partner_id=res.data.partner_id
//                    storage.set('partner_id',res.data.partner_id)
                        res.data.Integral.forEach((item)=>{
                            if (item.types==1){
                                storage.set('product_integra',item)
                            } else if (item.types == 2){
                                storage.set('comment_integra', item)
                            }
                        })

                        setTimeout(()=>{
                            if(storage.get('loginurl')){
                                var loginurl=storage.get('loginurl')
                                storage.remove('loginurl')
                                this.$router.replace({path:loginurl})
                            }else{
                                this.$router.replace({path:'/my'})
                            }
                        },1000)
                    })
                    .catch(err => console.log(err));
            },
            regPhone(){
                this.$router.push({path:"/my-reg-phone"})
            },
            getWxuserInfo(){

                // var url = window.location.href;
                // var locationurl = url.split('#')[0];
                /* var uid=serve.getParam('uid');
                 var uidPath='';
                 if(uid){
                     uidPath="?uid="+uid;
                 }else{
                     uidPath="?uid=";
                 }
                 this.axios.get('/authorization',{url:'https://c.kuaibangxing.com/quick_help_wap1/'+uidPath})*/
                storage.remove('partner_id')
                this.axios.get('/authorization',{url:'https://c.kuaibangxing.com/quick_help_wap1/'})
                    .then((res)=>{
                        window.location.href=res.data
                    //更新partner_id参数
                        window.localStorage.partner_id=res.data.partner_id
//                    console.log(res.data.partner_id,'33333333')
                    })
            },

          autoLogin() {
            let that = this;
            let now = new Date();
            let secret_code = now.toString();
            let strSecret = crypto.createHash('md5').update(that.loginKey + secret_code).digest("hex");

            let _params={
              username: that.fullUsername,
              clientId: that.clientId,
              secret_code: secret_code,
              secret: strSecret
            };

            return that.axios.postAll('api/member/driverGetToken', _params)
              .then(res =>{
                if(res.data.code === 200){

                  let userData = JSON.parse(res.data.data);
                  storage.set('userinfo', userData.data);
                  store.commit(types.LOGIN, userData.data.token);

                  // that.getData();
                  userData.data.Integral.forEach((item)=> {
                    if(item.types === 1){
                      storage.set('product_integra', item)
                    } else if (item.types === 2) {
                      storage.set('comment_integra', item)
                    }
                  });

                  if(storage.get('loginurl')){
                    let loginurl=storage.get('loginurl')
                    storage.remove('loginurl')
                    this.$router.replace({path:loginurl})
                  }else{
                    this.$router.replace({path:'/my'})
                  }
                }else{
                  Toast({message: res.data.msg, duration: 1000});
                }
              }).catch(err => {
                console.log(err)
              })
          },
        },
  /*      created(){
            this.isWechat = false;
            //判断URL中是否又飞拉旅行参数
           /!* window.localStorage.partner_id=judgeURL.getUrl("partner_id")  //||judgeURL.GetUrlPara()
            alert(storage.get('partner_id'))*!/
        },*/
        mounted(){
          let that = this;
            if (this.$route.query.redirect) {
                this.redirect = this.$route.query.redirect
            }
            if(!this.$store.state.token && this.isWechat){
                this.getWxuserInfo(); //请求微信授权
            }


          //监听RN发过来的消息
          document.addEventListener("message", function (data) {
            let message = data.data;
            let messageObject = JSON.parse(message);
            if (messageObject.command) {
              switch (messageObject.command) {
                case 'RNMessage' : {
                  // that.$toasted.show('RNMessage !!!');
                  break;
                }
                case 'AutoLogin' : {
                  store.commit('setAppNestState', true); //隐藏tab bar
                  let token = that.$store.state.token;
                  if(!that.fTryAutoLogin && (token === null)) {
                    that.fTryAutoLogin = true;

                    if (messageObject.content) {

                      that.fullUsername = messageObject.content.username;
                      that.clientId = messageObject.content.clientId;
                      that.loginKey = messageObject.content.loginKey;
                      that.appid = messageObject.content.appid;

                      if(that.appid && that.appid.length > 0) {
                        window.localStorage.appid = that.appid;
                      }
                      that.autoLogin();
                    }
                    break;
                  }
                  break;
                }
              }
            }
          });

        }
    }
</script>

<style lang="scss" scoped>
    @import "../assets/base";
    .bg{
        background: $bgcolor1;
        height: 100%;
    }
    .h30 {
        height: rpx(30);
        background: $bgcolor1
    }
    .h120 {
        height: rpx(120);
        background: $bgcolor1;
    }
    .header{
        display: flex;
        align-items: center;
        padding: rpx(10) rpx(30);
        justify-content: space-between;
        background:$color0;
        &-btnLeft{
            width: rpx(64);
            height: rpx(64);
            padding-top: rpx(8);
            img{
                width: rpx(48);
                height: rpx(48);
            }
        }
        &-btnRight:after{
            display: block;
            content: ' ';
            width: rpx(64);
            height: rpx(64);
        }
        &-title{
            flex: 1;
            font-size: rpx(36);
            text-align: center;
            font-weight: normal;
        }
    }
    .login{
        margin: rpx(30);
        background: $color0;
        &-item{
            flex: 1;
            display: flex;
            align-items: center;
            border-bottom: solid 1px $color2;
            padding: rpx(20) 0;
            height: rpx(110);
            &:last-child{
                border-bottom:none;
            }
            input{
                min-width: rpx(450);
                padding: rpx(10) rpx(30);
                font-size: rpx(34);
            }
        }
        &-code {
            height: 100%;
            background: #FB7D33;
            border-radius: $radius6;
            color: #ffffff;
            min-width: rpx(220);
            text-align: center;
            padding: rpx(20) rpx(10);
        }
        &-disabled {
            height: 100%;
            background: #cccccc;
            border-radius: $radius6;
            color: #ffffff;
            min-width: rpx(220);
            text-align: center;
            padding: rpx(20) rpx(10);
        }
        &-btn{
            padding: rpx(30);
            &-login{
                display: block;
                margin-bottom: rpx(30);
                border: none;
                width: 100%;
                height: rpx(100);
                line-height: rpx(100);
                background: $color3;
                border-radius: $radius6;
                color: $color0;
                font-size: rpx(34);
                text-align: center;
            }
            &-reg{
                display: block;
                box-sizing: border-box;
                margin-bottom: rpx(30);
                border: solid 1px $color3;
                width: 100%;
                height: rpx(100);
                line-height: rpx(100);
                background: $color0;
                border-radius: $radius6;
                color: $color3;
                font-size: rpx(34);
                text-align: center;

            }
        }
        &-other{
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: rpx(30) rpx(10);
            font-size: rpx(30);
        }
        &-weChat{
            display: flex;
            justify-content: center;
            align-items: center;
            flex-direction: column;
            &-logo{
                width: rpx(128);
                height: rpx(128);
            }
            &-name{
                padding: rpx(30) 0;
                font-size: rpx(36);

            }
        }
    }



</style>
